package test.client.thread.message;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.packet.Message;

import test.client.support.time.TimeTracker;
import test.client.thread.ClientThread;

public class ClientSenderThread extends ClientThread {
	private final int messageSleepTime = 5000;
	private int maxMessageCount = 3;
	private int currentMassageCount = 0;
	
	private String[] messages = new String[] {
			"hi~~~", 
			"how are you??", 
			"I'm fine thank you, and you??"
	};
	
	private String to;
	
	@Override
	public void run() {
		try {
			// notify the thread is started.
			this.notifyStarted();
			
			this.login();
			Thread.sleep(5000);
			
			this.sendMessage();
			
			// Wait until last echo message arrives 
			while (this.getStatus() == Status.RUNNING && !this.isAllMessageReceived()) {
				Thread.sleep(5000);
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.setResult(Result.FAILURE);
		}
		finally {
			this.setStatus(Status.COMPLETED);
			this.disconnect();
		}
	}
	
	private void sendMessage() throws Exception {
		for (String message : messages) {
			TimeTracker tracker = this.addTimeTracker();
			
			log.debug("[" + this.getUsername() + "] send message: " + message);
			tracker.start();
			this.sendMessage(message, to);
			Thread.sleep(messageSleepTime);
		}
	}
	
	@Override
	public void processMessage(Chat chat, Message message) {
		super.processMessage(chat, message);
		if (message.getType() != Message.Type.chat) return;
		
		try {
			// Process when receiving echo message
			int count = 0;
			for (String sent : messages) {
				if (message.getBody().contains(sent)) {
					this.getTimeTrackers().get(count).stop();
				}
				
				count++;
			}
			
			this.currentMassageCount++;
				
			log.debug("[" + this.getUsername() + "] process echo messages.. cur count: " + this.currentMassageCount);
			
			if (this.getStatus() == Status.RUNNING && isAllMessageReceived()) {
				this.setStatus(Status.COMPLETED);
				this.setResult(Result.SUCCESS);
				
				// notify the thread is stopped.
				this.notifyStopped();
			}
			
			log.debug("[" + this.getUsername() + "] isAllMessageReceived: " + isAllMessageReceived() + ", status: " + this.getStatus() + ", result: " + this.getResult());
		}
		catch (Exception e) {
			e.printStackTrace();
			this.setStatus(Status.COMPLETED);
			this.setResult(Result.FAILURE);
		}
	}
	
	private boolean isAllMessageReceived() {
		return this.maxMessageCount == this.currentMassageCount;
	}
	
	public void setMessages(String[] messages) {
		this.messages = messages;
	}

	public void setTo(String to) {
		this.to = to;
	}
	
	public static void main(String[] args) {
		ClientSenderThread thread = new ClientSenderThread();
		
		thread.setUsername("user000000");
		thread.setPassword("welcome1");
		
		thread.setTo("sejoonlim@openfire");
		thread.run();
	}
}
